package cn.remex.core.util;

import cn.remex.configuration.etcd.EtcdConfigCenter;
import cn.remex.core.exception.NestedException;
import cn.remex.core.exception.ServiceCode;

import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
 * 配置文件读取类
 */
public class PropertyReader {
	/**
	 * java读取配置文件
	 * @param clazz 对象
	 * @param propertyFile  配置文件名
	 * @return Properties 属性集
	 */
	private static Properties getProperties(final Class clazz, final String propertyFile) {
		try {
			InputStreamReader is = new InputStreamReader(clazz.getResourceAsStream(propertyFile),"gbk");
			Properties properties = new Properties();
			properties.load(is);
			return properties;
		} catch (Exception e) {
			throw new NestedException(ServiceCode.ERROR, "读取配置文件错误");
		}

	}

	/**
	 * 将配置文件转换成hashMap返回
	 * Retrieve the properties as Hashtable
	 * @param clazz 对象
	 * @param propertyFile 配置文件名
	 * @return a hashtable 哈希表
	 */
	@Deprecated
	public static HashMap<String, String> getPropertiesHashMap(final Class clazz, final String propertyFile) {
		Properties properties = getProperties(clazz, propertyFile);
		Enumeration<?> propNames = properties.propertyNames();
		HashMap<String, String> hashMap = new HashMap<>();
		while (propNames.hasMoreElements()) {
			String key = (String) propNames.nextElement();
			String value = properties.getProperty(key);
			hashMap.put(key, value);
		}
		return hashMap;
	}

	public static Map<String, String> getPropertiesMap(String propertyPrefix){
		return EtcdConfigCenter.getConfigMap(propertyPrefix);
	}
}
